package connections;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import main.UserInfo;
import message.Message;
import message.MessageType;
import message.NewClient;
import message.StartComunication;
import message.StopComunication;

/**
 * this class is in charge of running the dialog client->server
 * @author ran
 *
 */
public class SendMessageProtocol{
	ObjectInputStream in;
	ObjectOutputStream out;
	MessageHandler handler=new MessageHandler();
	/**
	 * constructor of the class, reset the members of the class
	 * @param in - input stream object
	 * @param out - output stream object
	 */
	public SendMessageProtocol(ObjectInputStream in, ObjectOutputStream out) {
		this.in=in;
		this.out=out;
	}
	

	/**
	* manage the dialog client -> server
	*/
	public void runProtocol(Object message){
		Message returnedMessage = null;
		boolean contin = true;
		try{
			if( message instanceof NewClient)
				out.writeObject(new StartComunication("client","client","client"));
			else{
				out.writeObject(new StartComunication(UserInfo.getInstance().getUserName(),UserInfo.getInstance().getPass(),UserInfo.getInstance().getComputerName()));
			}
			returnedMessage=(Message)in.readObject();
			//the first message that the user need to send
			if(returnedMessage.getType()==MessageType.START_COMUNICATION){
				StartComunication serverStart = (StartComunication)returnedMessage;
				//the server validate user name & password
				if(serverStart.getPass().compareTo("server")!=0)
					System.out.println("bad user name or password!");
			}
			//send message to the server
			out.writeObject(message);
			//loop that implements the dialog client - > server
			while(contin){//(returnedMessage = (Message)in.readObject()).getType()!=MessageType.STOP_COMUNICATION){
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				returnedMessage = (Message)in.readObject();
				Message messageToServer=null;
				messageToServer=handler.interpretMessage(returnedMessage);
				if(messageToServer==null)
					System.out.println("message null");
				if(messageToServer.getType()==MessageType.STOP_COMUNICATION)
					contin=false;
				//send message to the server
				out.writeObject(messageToServer);
			}
			//send end communication message to the server
			out.writeObject(new StopComunication());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	
}
